<template>
  <page-meta root-font-size="16px"></page-meta>
  <view class="page">
    <view class="top-container"
          :style="{ backgroundImage: `url(${imgUrl})`,paddingTop:`${sysInfo.statusBarHeight}px` }">
      <view class="flex-row" :style="{ height: `${sysInfo.navigationBarHeight}px`}">
        <u-icon name="arrow-left" color="#fff" @click="handleToBack"></u-icon>
        <text>海报分享</text>
        <view class="blank"></view>
      </view>
    </view>

    <view class="content">
      <l-painter ref="painter"
                 pathType="url"
                 :board="poster"
                 isCanvasToTempFilePath
                 @success="path = $event"
                 hidden
      >
      </l-painter>
      <view class="canvas-wrapper">
        <image :src="path" mode="widthFix" style="width: 100%;height: 100%"></image>
      </view>
      <view class="flex-row">
        <u-button type="primary" :customStyle="styleLeft" text="更改模板" @click="handleToChangePoster"></u-button>
        <u-button type="primary" :customStyle="styleLeft" text="保存图片" @click="savePhoto"></u-button>
        <u-button type="primary" :customStyle="styleRight" plain text="新闻分享" @click="handleToNews"></u-button>
      </view>
    </view>
  </view>
</template>

<script>
import bgBase64 from "@/static/const/bgBase64";
import config from "@/config";
import {getImgUrl, isEmptyArray, isEmptyString} from "@/utils/common";
import QSCanvas from "@/js_sdk/QuShe-SharerPoster/index.js";
import {getPicDetail} from "@/api/photo/photo";
import {getStorage} from "@/utils/auth";
import application from "@/static/const/application";

var qsc;
export default {
  name: "index",
  data() {
    return {
      imgUrl: bgBase64.inviteFriendBg,
      footSize: this.$fontSize,
      invitePhoto: [],
      styleLeft: {
        width: "30%",
        height: "40px",
        fontSize: "14px",
        color: "#fff",
        backgroundColor: "#E44433",
        borderColor: "#E44433",
      },
      styleRight: {
        width: "30%",
        height: "40px",
        fontSize: "14px",
        color: "#E44433",
        borderColor: "#E44433",

      },
      sysInfo: {
        statusBarHeight: 0, // 状态导航栏高度
        navHeight: 0, // 总体高度
        navigationBarHeight: 128, // 导航栏高度(标题栏高度)
      },
      posterUrl: "https://x.lcfawu.com/profile/upload/2023/02/16/391ae6d452a5e54df04ced24c289bf73_20230216151452A002.gif",
      inviteUrl: "",
      idShow: false,
      path: "",
      hidden: true,
      poster: {
        css: {
          width: "800rpx",
          background: "linear-gradient(,#000 0%, #ff5000 100%)"
        },
        views: [
          {
            css: {
              width: "100%",
              height: "100%",
              position: "relative",
            },
            views: [
              {
                src: "https://x.lcfawu.com/profile/upload/2023/02/16/391ae6d452a5e54df04ced24c289bf73_20230216151452A002.gif",
                type: "image",
                css: {
                  objectFit: "cover",
                  objectPosition: "50% 50%",
                  width: "100%",
                  height: "100%"
                },
              },
              {
                text: "https://www.baidu.com",
                type: "qrcode",
                css: {
                  width: "128rpx",
                  height: "128rpx",
                  position: "absolute",
                  bottom: "5%",
                  left: "40%",
                },

              }
            ],
            type: "view"
          }
        ]
      }
    };
  },
  onLoad(params) {
    this.getInfo();
    this.getData(params);

  },
  onShow() {

  },
  methods: {
    //获取图片详情
    getData(params) {
      //获取屏幕宽度
      const sysInfo = uni.getSystemInfoSync().windowWidth;
      //获取userID
      const userID = getStorage(application.user).userId;
      //拼装邀请链接
      this.inviteUrl = `${config.qrcodeUrl}/weixin/?invitationId=${userID}`;
      if (this.inviteUrl === null || this.inviteUrl === undefined || this.inviteUrl === '') {
        this.inviteUrl = config.baseUrl;
      }
      if (params.id === null || params.id === undefined || params.id === '') {
        this.posterUrl = this.posterUrl;
        this.poster = {
          css: {
            width: sysInfo+"px",
            background: "linear-gradient(,#000 0%, #ff5000 100%)"
          },
          views: [
            {
              css: {
                width: "100%",
                height: "100%",
                position: "relative",
              },
              views: [
                {
                  src: this.posterUrl,
                  type: "image",
                  css: {
                    objectFit: "cover",
                    objectPosition: "50% 50%",
                    width: "100%",
                    height: "100%"
                  },
                },
                {
                  text: this.inviteUrl,
                  type: "qrcode",
                  css: {
                    width: "128rpx",
                    height: "128rpx",
                    position: "absolute",
                    bottom: "5%",
                    left: "40%",
                  },

                }
              ],
              type: "view"
            }
          ]
        };
      } else {
        this.getPhoto(params.id);
      }
    },
    //获取标题栏高度
    getInfo() {
      // 状态栏高度
      this.sysInfo.statusBarHeight = uni.getSystemInfoSync().statusBarHeight

      // #ifdef MP-WEIXIN
      // 获取微信胶囊的位置信息 width,height,top,right,left,bottom
      const custom = wx.getMenuButtonBoundingClientRect()
      // console.log(custom)

      // 导航栏高度(标题栏高度) = 胶囊高度 + (顶部距离 - 状态栏高度) * 2
      this.sysInfo.navigationBarHeight = custom.height + (custom.top - this.sysInfo.statusBarHeight) * 2
      // console.log("导航栏高度："+this.globalData.navigationBarHeight)

      // 总体高度 = 状态栏高度 + 导航栏高度
      this.sysInfo.navHeight = this.sysInfo.navigationBarHeight + this.sysInfo.statusBarHeight

      // #endif
    },

    async getPhoto(id) {
      const sysInfo = uni.getSystemInfoSync().windowWidth;
      let url = this.posterUrl;
      try {
        const res = await getPicDetail(id);
        const arr = getImgUrl(res.data.content);
        url = arr[0];
        this.poster = {
          css: {
            width: sysInfo+"px",
            background: "linear-gradient(,#000 0%, #ff5000 100%)"
          },
          views: [
            {
              css: {
                width: "100%",
                height: "100%",
                position: "relative",
              },
              views: [
                {
                  src: url,
                  type: "image",
                  css: {
                    objectFit: "cover",
                    objectPosition: "50% 50%",
                    width: "100%",
                    height: "100%"
                  },
                },
                {
                  text: this.inviteUrl,
                  type: "qrcode",
                  css: {
                    width: "128rpx",
                    height: "128rpx",
                    position: "absolute",
                    bottom: "5%",
                    left: "40%",
                  },

                }
              ],
              type: "view"
            }
          ]
        };

      } catch (e) {
        url = this.posterUrl;
        console.log(e);
      }
      // await this.drawPoster(url);
    },
    //保存图片
    savePhoto() {
      uni.showModal({
        title: '提示',
        content: '确定保存到相册吗',
        success: (response) => {
          this.$refs.painter.canvasToTempFilePathSync({
            fileType: "png",
            // 如果返回的是base64是无法使用 saveImageToPhotosAlbum，需要设置 pathType为url
            pathType: 'url',
            quality: 1,
            success: (res) => {
              console.log(res.tempFilePath);
              // 非H5 保存到相册
              // H5 提示用户长按图另存
              uni.saveImageToPhotosAlbum({
                filePath: res.tempFilePath,
                success: function () {
                  console.log('save success');
                }
              });
            },
          });

          // uni.canvasToTempFilePath({
          //   x: 0,
          //   y: 0,
          //   height: 480,
          //   width: 320,
          //   canvasId: 'poster',
          //   success: (response) => {
          //     uni.saveImageToPhotosAlbum({
          //       filePath: response.tempFilePath,
          //       success: (response) => {
          //         uni.showToast({
          //           title: '保存成功',
          //           icon: 'success',
          //           duration: 2000
          //         })
          //       },
          //       fail: (response) => {
          //         uni.openSetting({
          //           success: (response) => {
          //             if (!response.authSetting['scope.writePhotosAlbum']) {
          //               uni.showModal({
          //                 title: '提示',
          //                 content: '获取权限成功，再次点击图片即可保存',
          //                 showCancel: false
          //               })
          //             } else {
          //               uni.showModal({
          //                 title: '提示',
          //                 content: '获取权限失败，无法保存',
          //                 showCancel: false
          //               })
          //             }
          //           }
          //         })
          //       }
          //     })
          //   },
          //   fail: (response) => {
          //     uni.showToast({
          //       title: '保存失败',
          //       icon: 'none',
          //       duration: 2000
          //     })
          //   }
          // }, this);
        }
      });
    },
    // 返回上一页
    handleToBack() {
      console.log("返回上一页");
      uni.navigateBack({
        delta: 1
      });
    },
    // 跳转到到更改海报
    handleToChangePoster() {
      console.log("跳转到到更改海报");
      uni.redirectTo({
        url: "/pages/invite/changePoster/index",
      });
    },
    // 跳转到新闻分享
    handleToNews() {
      console.log("跳转到新闻分享");
      uni.switchTab({
        url: "/pages/news/index",
      });
    },
    // 保存图片
    saveImageFromCanvas(width, height) {
      let self = this;
      uni.canvasToTempFilePath(
          {
            x: 0,
            y: 0,
            height: height,
            width: width,
            canvasId: "poster",
            success: (response) => {
              // #ifdef APP-PLUS
              uni.saveImageToPhotosAlbum({
                filePath: response.tempFilePath,
                success: (response) => {
                  console.log("保存图片成功");
                },
                fail: (response) => {
                  console.log("保存图片失败");
                },
              });
              return;
              // #endif

              self.tempFilePath = response.tempFilePath;
              self.isPosterShow = true;
              uni.hideLoading();
            },
            fail: (response) => {
              uni.hideLoading();
              // toast("生成海报失败");
            },
          },
          this
      );
    },
    // 绘制海报
    async drawPoster(poster) {
      console.log("绘制海报");
      try {
        const canvasWidth = 20 * 16;
        const canvasHeight = 30 * 16;


        // 背景色
        qsc.setRect({x: 0, y: 0, r: 50, height: canvasHeight, width: canvasWidth});
        qsc.saveAndSetPaintbrush({
          fillStyle: "#fff",
        });
        qsc.fill();
        console.log("------->");

        // 海报
        if (poster) {
          console.log("postrer-------", poster)
          await qsc.drawImg({
            val: poster,
            x: 0,
            y: 0,
            r: 50,
            mode: 'scaleToFill',
            height: canvasHeight,
            width: canvasWidth,
          });
        }
        console.log("------->00000000000");

        // 二维码
        await qsc.drawQrCode({
          val: this.inviteUrl,
          x: canvasWidth / 2 - uni.upx2px(50),
          y: canvasHeight - uni.upx2px(150),
          size: uni.upx2px(100),
        });
        console.log("------->11111111111");

        await qsc.updateCanvasWH({width: canvasWidth, height: canvasHeight});
        await qsc.draw();
        console.log("------->22222222222222");

        this.saveImageFromCanvas(canvasWidth, canvasHeight);
      } catch (e) {
        console.log("------->ERR...", e);
        // toast("获取海报错误");
      }
    },
  },
}
</script>

<style scoped lang="scss">
page {
  position: relative;
  height: 100vh;

  .top-container {
    width: 100%;
    height: 10rem;
    background-size: cover;

    .flex-row {
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 0 10px;

      text {
        font-size: 1rem;
        color: #fff;
      }

      .blank {
        width: 1rem;
      }
    }
  }

  .content {
    position: absolute;
    top: 8rem;
    width: 100%;
    height: calc(100% - 8rem);
    background-color: #fff;
    border-top-left-radius: 50px;
    border-top-right-radius: 50px;
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    padding: 20px 40px 2rem;

    .flex-row {
      margin-top: 2rem;
      width: 100%;
      justify-content: space-evenly;
    }
  }
}

.canvas-wrapper {
  width: 100%;
  height: 100%;
  padding: 0 20px;
  display: flex;
  justify-content: center;
  align-items: center;
  position: relative;

  .canvas {
    position: fixed;
  }
}
</style>